package com.project.common.exception;


import com.fasterxml.jackson.databind.JsonMappingException;
import com.project.common.operation.Result;
import com.project.constants.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolationException;
import java.text.MessageFormat;
import java.util.Iterator;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseEntity<?> processException(NativeWebRequest request, NoHandlerFoundException e) {
        String code = ErrorCode.ERR_404.getCode();
        String msg = MessageFormat.format(ErrorCode.ERR_404.getErrorMessage(), e.getHttpMethod(), e.getRequestURL());
        log.warn(msg);
        return ResponseEntity.ok(Result.failure(code, msg));
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<?> processException(NativeWebRequest request, MissingServletRequestParameterException e) {
        String code = ErrorCode.ERR_MISS_PARAM_ERROR.getCode();
        String msg = MessageFormat.format(ErrorCode.ERR_MISS_PARAM_ERROR.getErrorMessage(), e.getParameterType(), e.getParameterName());
        log.warn(msg);
        return ResponseEntity.ok(Result.failure(code, msg));
    }


    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<?> processException(NativeWebRequest request, MethodArgumentTypeMismatchException e) {
        String code = ErrorCode.ERR_MISS_PARAM_ERROR.getCode();
        String msg = MessageFormat.format(ErrorCode.ERR_MISS_PARAM_TYPE_ERROR.getErrorMessage(), e.getName());
        log.warn(msg);
        return ResponseEntity.ok(Result.failure(code, msg));
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public ResponseEntity<?> processException(NativeWebRequest request, HttpRequestMethodNotSupportedException e) {
        String code = ErrorCode.ERR_REQUEST_METHOD_ERROR.getCode();
        String msg = MessageFormat.format(ErrorCode.ERR_REQUEST_METHOD_ERROR.getErrorMessage(), e.getMethod(), e.getSupportedHttpMethods().toString());
        log.warn(msg);
        return ResponseEntity.ok(Result.failure(code, msg));
    }

    @ExceptionHandler(AssertsException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseEntity<?> processException(NativeWebRequest request, AssertsException e) {
        log.warn(e.getMsg());
        return ResponseEntity.ok(Result.failure(e.getCode(), e.getMessage()));
    }

    @ExceptionHandler(GlobalException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseEntity<?> processException(NativeWebRequest request, GlobalException e) {
        log.error(e.getMsg(), e);
        return ResponseEntity.ok(Result.failure(e.getCode(), e.getMsg()));
    }


    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseEntity<?> processException(NativeWebRequest request, RuntimeException e) {
        log.error("运行时异常：{}", e.getMessage(), e);
        return ResponseEntity.ok(Result.failure(ErrorCode.ERR_SERVER_ERR.getCode(), e.toString()));
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseEntity<?> processException(NativeWebRequest request, Exception e) {

        if (e instanceof MethodArgumentNotValidException || e instanceof ConstraintViolationException
                || e instanceof JsonMappingException || e instanceof HttpMessageNotReadableException
                || e instanceof HttpMessageNotWritableException || e instanceof HttpRequestMethodNotSupportedException
                || e instanceof ServletRequestBindingException) {
            return ResponseEntity.ok(Result.failure(ErrorCode.PARAM_ERROR.getCode(), getParamErrorDetails(e)));
        }

        log.error("服务器错误：{}", e.getMessage(), e);
        return ResponseEntity.ok(Result.failure(ErrorCode.ERR_BASE_ERR.getCode(), e.toString()));
    }

    private String getParamErrorDetails(Exception e) {
        StringBuffer sb = new StringBuffer();
        if (e instanceof MethodArgumentNotValidException) {
            Iterator var = ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors().iterator();
            while (var.hasNext()) {
                ObjectError error = (ObjectError) var.next();
                DefaultMessageSourceResolvable messageSourceResolvable = (DefaultMessageSourceResolvable) error.getArguments()[0];
                sb.append("[key=");
                sb.append(messageSourceResolvable.getCode());
                sb.append(",");
                sb.append(error.getDefaultMessage()).append("]");
            }
        }
        if (e instanceof MissingServletRequestParameterException) {
            sb.append("[key=");
            sb.append(((MissingServletRequestParameterException) e).getParameterName());
            sb.append("],").append(e.getMessage());
        }
        if (e instanceof HttpMessageNotReadableException) {
            sb.append(e.getLocalizedMessage());
        }
        if (StringUtils.isBlank(sb.toString())) {
            sb.append(e.getMessage());
        }
        return sb.toString();
    }
}
